package cn.edu.usst.cs.goldfish.booking.meetingroom.mybatis;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.io.*;
import java.util.logging.Logger;

import org.jetbrains.annotations.NotNull;
import org.slf4j.LoggerFactory;

@Mapper
public interface ExceptionMapper {
    @Insert("INSERT INTO public.exception(id, trace) VALUES(#{id}, #{trace})")
    void save(Long id,
            String trace);

    @Select("SELECT id FROM exception WHERE trace=#{content}")
    Long findTimeByContent(@Param("content") String content);

    @Select("SELECT trace FROM exception WHERE id= #{id}")
    String findContentById(@Param("id") Long id);

    @Select("SELECT (MAX(id)+1) FROM exception")
    Long minFreeId();

    default void insert(Exception e) {
        Long id = minFreeId();
        if (id == null) {
            id = 1L;
        }
        String trace = getTrace(e);
        save(id, trace);
    }

    @NotNull
    default String getTrace(Exception e) {
        StringWriter writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        String trace = writer.toString();
        var slf4jLogger = LoggerFactory.getLogger(ExceptionMapper.class);
        slf4jLogger.error(trace);
        return trace;
    }

}